package fcrypt

import (
	"fmt"
	"strings"
)

//栅栏密码
func RailEnc(plain string, row int) string {
	plainByte := []byte(plain)
	plainLen := len(plainByte)
	col := 0
	if plainLen%row == 0 {
		col = plainLen / row
	} else {
		col = plainLen/row + 1
	}
	matricsLen := row * col
	restLen := matricsLen - plainLen
	if restLen > 0 {
		for i := 0; i < restLen; i++ {
			plainByte = append(plainByte, []byte("+")...)
		}
	}
	fmt.Println(plainByte)

	cipherByte := make([]byte, matricsLen)
	for k := 0; k < matricsLen; k++ {
		cipherByte[k] = plainByte[row*(k%col)+k/col]
	}
	cipherStr := string(cipherByte)
	fmt.Println(cipherStr)
	cipherStr = strings.ReplaceAll(cipherStr, "+", "")
	return cipherStr
}

func RailDec(cipher string, row int) string {
	cipherByte := []byte(cipher)
	cipherLen := len(cipherByte)
	col := 0
	matricsLen := 0
	restLen := 0
	if cipherLen%row == 0 {
		col = cipherLen / row
	} else {
		col = cipherLen/row + 1
	}
	matricsLen = row * col
	restLen = matricsLen - cipherLen

	if restLen > 0 {
		i := cipherLen
		for k := 0; k < restLen; k++ {
			cipherByte = append(cipherByte, 0)
			copy(cipherByte[i:], cipherByte[i-1:])
			cipherByte[i] = 0x2b
			i -= (col - 1)
		}
	}

	plainByte := make([]byte, matricsLen, matricsLen)
	for k := 0; k < matricsLen; k++ {
		plainByte[k] = cipherByte[col*(k%row)+k/row]
	}
	plainStr := strings.ReplaceAll(string(plainByte), "+", "")
	return plainStr
}
